// page/component/new-pages/cart/cart.js
// 默认请求第一页
var numbers = 1;
var bool = true;
Page({
  data: {
    userId: '',
    //所有购物车信息
    allList: [],
    //当前列表数据
    // list: [],
    show_edit: "block",
    edit_name: "编辑",
    edit_show: "none",
    // list: [],               // 购物车列表
    // hasList: false,          // 列表是否有数据
    // 默认展示数据
    hasList: true,
    // 金额
    totalPrice: 0, // 总价，初始为0
    // 全选状态
    selectAllStatus: 1, // 全选状态，默认全选
  },

  /* 获取地址信息 */
  getVisitInfo() {
    var url = wx.getStorageSync("config")
    let that = this;
    let id = that.data.id;
    wx.request({
      url: url.service.homeUrl + "/huiguniang/address/fetch?id=3&userId=" + id,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        if (res.data.status.code === 1) {
          let temInfo = res.data.result;
          that.setData({
            visitList: temInfo
          })
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  onLoad: function() {
    //获取用户id
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userId: userInfo.openId
    });
    //获取购物车信息
    this.getCartList();
  },

  onShow: function() {
    this.getCartList();
  },

  /* 获取购物车信息 */
  getCartList: function() {
    var url = wx.getStorageSync("config")
    let that = this;
    let userId = that.data.userId;
    wx.request({
      url: url.service.homeUrl + "/huiguniang/shopcar/selectAll?openId=" + userId,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data.status.returnCode === 1) {
          let list = res.data.result;
          // console.log(list)
          let allPrice = 0; //总价
          // for (let m = 0; m < allList.length; m++) {
          // let list = allList[m];
          let newList = [];
          // console.log("chakan");
          // console.log(list);
          let temPrice = 0; //每个店铺的总价
          for (let i = 0; i < list.length; i++) {
            let listOption = {};
            listOption.id = list[i].productId;
            listOption.title = list[i].productName;
            listOption.image = list[i].imagePath;
            listOption.num = list[i].productNumber;
            listOption.price = list[i].productPrice;
            listOption.pro_name = list[i].productIntroduce;
            listOption.specification = list[i].specification;
            listOption.selected = list[i].selected;
            if (list[i].selected === 1) {
              temPrice = temPrice + list[i].productNumber * list[i].productPrice;
            }
            newList.push(listOption)
          }
          allPrice = allPrice + temPrice;
          list = newList;
          // }
          console.log("加载购物车")
          // console.log(list)
          that.setData({
            allList: list,
            totalPrice: allPrice,
            imgUrl: url.service.imgUrl
          })
          that.allSelect();
          if (!list.length) {
            that.setData({
              hasList: false
            });
          }
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  onShow() {
    wx.showToast({
      title: '加载中',
      icon: "loading",
      duration: 1000
    })
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    console.log("selectList")
    console.log(e)
    var url = wx.getStorageSync("config")
    var that = this;
    let userId = that.data.userId;
    var productId = e.currentTarget.dataset.id;
    let selected = e.currentTarget.dataset.selected;
    let num = e.currentTarget.dataset.num;
    if (selected === 1) {
      selected = 0;
    } else {
      selected = 1;
    }
    console.log("productId:" + productId)
    console.log("selected:" + selected)
    console.log("num:" + num)
    wx.request({
      url: url.service.homeUrl + "/huiguniang/shopcar/updateShopCar?openId=" + userId + "&productId=" + productId + "&productNumber=" + num + "&selected=" + selected,
      method: 'PUT',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data.status.returnCode === 1) {
          that.getCartList();
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 编辑
  btn_edit: function() {
    var that = this;
    if (bool) {
      that.setData({
        edit_show: "block",
        edit_name: "取消",
        show_edit: "none"
      })
      bool = false;
    } else {
      that.setData({
        edit_show: "none",
        edit_name: "编辑",
        show_edit: "block"
      })
      bool = true;
    }

  },
  // 删除
  deletes: function(e) {
    // console.log(e)
    var that = this;
    // 获取索引
    const index = e.currentTarget.dataset.index;
    const productId = e.currentTarget.dataset.id;
    // 获取商品列表数据
    let list = this.data.list;
    wx.showModal({
      title: '提示',
      content: '确认删除吗',
      success: function(res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击确定
          var url = wx.getStorageSync("config")
          let userId = that.data.userId;
          wx.request({
            url: url.service.homeUrl + "/huiguniang/shopcar/deleteProduct?openId=" + userId + "&productId=" + productId,
            method: 'DELETE',
            header: {
              'Content-Type': 'application/json'
            },
            success: function(res) {
              // console.log(res)
              if (res.data.status.returnCode === 1) {
                that.getCartList();
              }
            },
            fail: function(res) {},
            complete: function(res) {},
          })
        }
      },
      fail: function(res) {
        // console.log(res);
      }
    })
  },

  /* 判断全选按钮 */
  allSelect() {
    let allList = this.data.allList;
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = 1;
    // console.log(allList.length)
    // for (let m = 0; m < allList.length; m++) {
    //每个店铺里的商品list
    let list = allList;
    // 每个店铺的总价
    let temPrice = 0;
    for (let i = 0; i < allList.length; i++) {
      if (allList[i].selected === 0) {
        selectAllStatus = 0;
        break;
      }
    }
    // }
    this.setData({
      selectAllStatus: selectAllStatus
    })
  },



  /* 绑定加数量事件 */
  btn_add(e) {
    var url = wx.getStorageSync("config")
    let that = this;
    let userId = that.data.userId;
    let productId = e.currentTarget.dataset.id;
    let numm = e.currentTarget.dataset.num + 1;
    let selected = e.currentTarget.dataset.selected;
    wx.request({
      url: url.service.homeUrl + "/huiguniang/shopcar/updateShopCar?openId=" + userId + "&productId=" + productId + "&productNumber=" + numm + "&selected=" + selected,
      method: 'PUT',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data.status.returnCode === 1) {
          that.getCartList();
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  canvas: function(object) {
    let _this = this;
    let realWidth, realHeight;
    //创建节点选择器
    var query = wx.createSelectorQuery();
    //选择id
    query.select('#mycanvas').boundingClientRect()
    query.exec(function(res) {
      //res就是 该元素的信息 数组
      realWidth = res[0].width;
      realHeight = res[0].height;
      console.log('realHeight', realHeight);
      console.log('realWidth', realWidth);
      const ctx = wx.createCanvasContext('mycanvas');
      ctx.drawImage("../../images/ctx-bg.jpg", 0, 0, realWidth, realHeight);
      ctx.drawImage(_this.data.canvasUserPic, (realWidth * 0.099), (realHeight * 0.052), (realWidth * 0.091), (realWidth * 0.091));
      ctx.setFontSize(12);
      ctx.setFillStyle("#a38874");
      ctx.fillText(object.date, (realWidth * 0.201), (realHeight * 0.076));
      ctx.setFontSize(14);
      ctx.setFillStyle("#a38874");
      ctx.fillText("农历" + object.lunar, (realWidth * 0.201), (realHeight * 0.099));
      ctx.drawImage("../../images/swiper-bg.png", (realWidth * 0.099), (realHeight * 0.112), (realWidth * 0.8), (realHeight * 0.60));
      ctx.drawImage(_this.data.canvasShowImg, (realWidth * 0.099), (realHeight * 0.112), (realWidth * 0.8), (realHeight * 0.30));
      ctx.drawImage("../../images/swiper-detail.png", (realWidth * 0.099), (realHeight * 0.395), (realWidth * 0.8), (realHeight * 0.03));
      ctx.setFontSize(16);
      ctx.setFillStyle("#8d7665");

      ctx.setTextAlign('center')
      ctx.fillText(object.title1, realWidth / 2, _this.calculateWH(2, 620, realWidth, realHeight));
      ctx.fillText(object.title2, realWidth / 2, _this.calculateWH(2, 666, realWidth, realHeight));

      ctx.drawImage("../../images/swiper-line.png", (realWidth - realWidth * 0.71) / 2, (realHeight * 0.528), (realWidth * 0.71), (realHeight * 0.0195));
      ctx.drawImage("../../images/luckpic.png", _this.calculateWH(1, 267, realWidth, realHeight), _this.calculateWH(2, 763, realWidth, realHeight), _this.calculateWH(1, 204, realWidth, realHeight), _this.calculateWH(2, 60, realWidth, realHeight));
      ctx.setFontSize(12);
      ctx.fillText(object.luck_title, realWidth / 2, _this.calculateWH(2, 880, realWidth, realHeight));
      ctx.drawImage("../../images/code.jpg", _this.calculateWH(1, 229, realWidth, realHeight), _this.calculateWH(2, 989, realWidth, realHeight), _this.calculateWH(1, 292, realWidth, realHeight), _this.calculateWH(1, 292, realWidth, realHeight))
      ctx.draw();

      setTimeout(function() {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: function(res) {
            var tempFilePath = res.tempFilePath;
            _this.setData({
              canvasUrl: tempFilePath
            })
            if (tempFilePath !== '') {
              _this.setData({
                isShowCav: false
              });
              wx.hideLoading();
              wx.previewImage({
                current: _this.data.canvasUrl, // 当前显示图片的http链接  
                urls: [_this.data.canvasUrl], // 需要预览的图片http链接列表  
              })
            }
          },
          fail: function(res) {
            console.log(res);
          }
        });
      }, 500);
    })
  }, //下载图片
  onShow1: function(object) {
    let _this = this;
    _this.setData({
      isShowCav: true
    })
    wx.downloadFile({
      url: object.avatarurl,
      success: function(sres) {
        _this.setData({
          canvasUserPic: sres.tempFilePath
        });
        wx.downloadFile({
          url: object.show_img,
          success: function(sres1) {
            _this.setData({
              canvasShowImg: sres1.tempFilePath
            });
            _this.canvas(object);
          }
        })
      }
    })
  },
  /**
   * 绑定减数量事件
   */
  btn_minus(e) {
    var url = wx.getStorageSync("config")
    let that = this;
    let userId = that.data.userId;
    let productId = e.currentTarget.dataset.id;
    let selected = e.currentTarget.dataset.selected;
    let numm = e.currentTarget.dataset.num - 1;
    wx.request({
      url: url.service.homeUrl + "/huiguniang/shopcar/updateShopCar?openId=" + userId + "&productId=" + productId + "&productNumber=" + numm + "&selected=" + selected,
      method: 'PUT',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data.status.returnCode === 1) {
          that.getCartList();
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 提交订单
  btn_submit_order: function() {
    let allList = this.data.allList;
    let confirmList = [];
    // for (let i = 0; i < allList.length; i++){
    // let list = allList[i].list;
    for (let j = 0; j < allList.length; j++) {
      let option = {};
      if (allList[j].selected === 1) {
        option = allList;
        confirmList.push(option);
      }
    }
    // }
    if (confirmList.length === 0) {
      wx.showToast({
        title: '您还没有选择商品哦！',
        icon: 'none'
      })
    } else {
      wx.navigateTo({
        url: '../sureOrder/sureOrder',
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    }
  },
  // 收藏
  // btn_collert: function() {
  //   wx.showToast({
  //     title: '收藏暂未开发',
  //     duration: 2000
  //   })
  // },



  /**
   * 购物车全选事件
   */
  selectAll(e) {
    var url = wx.getStorageSync("config")
    let that = this;
    let userId = that.data.userId;
    let selectAllStatus = that.data.selectAllStatus;
    if (selectAllStatus === 1) {
      selectAllStatus = 0;
    } else {
      selectAllStatus = 1;
    }

    wx.request({
      url: url.service.homeUrl + "/huiguniang/shopcar/allSelect?openId=" + userId + "&selected=" + selectAllStatus,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data.status.returnCode === 1) {
          that.getCartList();
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })

    this.setData({
      selectAllStatus: selectAllStatus
    })
  },

  onShow() {
    this.getCartList();
  }
})